using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Modeling;
using Volo.Abp.EntityFrameworkCore.DependencyInjection;
using Joy.Erp.BasicArchives.EntityFrameworkCore;

namespace Joy.Erp.BasicArchives.Suppliers
{
    public class SupplierModelConfiguration : IModelConfiguration
    {
        public void Build(ModelBuilder builder)
        {
            builder.Entity<Supplier>(b =>
            {
                b.ToTable(BasicArchivesDbProperties.DbTablePrefix + nameof(Supplier), BasicArchivesDbProperties.DbSchema);
                b.ConfigureByConvention();
                b.ConfigureArchiveAggregateRoot();

                b.Property(x => x.Name).HasMaxLength(SupplierConsts.NameMaxLength);
                b.Property(x => x.Name).IsRequired(SupplierConsts.NameRequired);
                b.Property(x => x.ShortName).HasMaxLength(SupplierConsts.ShortNameMaxLength);
                b.Property(x => x.ShortName).IsRequired(SupplierConsts.ShortNameRequired);
                b.Property(x => x.Contact).HasMaxLength(SupplierConsts.ContactMaxLength);
                b.Property(x => x.Phone).HasMaxLength(SupplierConsts.PhoneMaxLength);
                b.Property(x => x.Address).HasMaxLength(SupplierConsts.AddressMaxLength);

                b.HasOne(x => x.SupplierType).WithMany().HasForeignKey(x => x.SupplierTypeId).OnDelete(DeleteBehavior.Restrict);
                b.HasOne(x => x.Operator).WithMany().HasForeignKey(x => x.OperatorId).OnDelete(DeleteBehavior.Restrict);
            });
        }

        public void Entity(IAbpDbContextRegistrationOptionsBuilder options)
        {
            options.Entity<Supplier>(opt =>
            {
                opt.DefaultWithDetailsFunc = query =>
                {
                    return query
                        .Include(x => x.SupplierType)
                        .Include(x => x.Operator)
                        ;
                };
            });
        }
    }
}